package com.qdlc.p2p.biz.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.qdlc.p2p.biz.service.ExperienceRuleService;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.model.jpa.OrderFilter.OrderType;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter.Operators;
import com.qdlc.p2p.dal.dao.ExperienceRuleDao;
import com.qdlc.p2p.dal.dto.ExperienceRule;
import com.qdlc.p2p.dal.model.ExperienceRuleModel;

/**
 * 体验券规则service实现类
 *
 * @author xxx
 * @version 2.0
 * @date 2015年4月23日 下午8:02:57
 */
@Repository("experienceRuleService")
public class ExperienceRuleServiceImpl implements ExperienceRuleService {

    @Resource
    private ExperienceRuleDao experienceRuleDao;

    @Override
    public List<ExperienceRule> findUsableExperienceRule() {
        return experienceRuleDao.findByProperty("status", ExperienceRuleModel.EXPERIENCERULE_STATUS_ENABLE);
    }

    @Override
    public PageDataList<ExperienceRule> findByModel(ExperienceRuleModel model) {
        QueryParam param = QueryParam.getInstance();
        if (StringUtil.isNotBlank(model.getSearchName())) {//模糊查询条件
            param.addParam("name", Operators.LIKE, model.getSearchName());
        } else {
            if (model.getStatus() != 99) {
                param.addParam("status", model.getStatus());
            }
            if (!StringUtil.isBlank(model.getReceiveStartTime())) {
                param.addParam("addTime", Operators.GT, DateUtil.valueOf(model.getReceiveStartTime()));
            }
            if (!StringUtil.isBlank(model.getReceiveEndTime())) {
                Date date = DateUtil.valueOf(model.getReceiveEndTime());
                param.addParam("addTime", Operators.LT, DateUtil.rollDay(date, 1));
            }
        }
        param.addPage(model.getPage(), model.getRows());
        param.addOrder(OrderType.DESC, "id");
        PageDataList<ExperienceRule> pageDataList = experienceRuleDao.findPageList(param);
        return pageDataList;
    }

    @Override
    public void save(ExperienceRule experienceRule) {
        experienceRuleDao.save(experienceRule);
    }

    @Override
    public ExperienceRule findById(long id) {
        return experienceRuleDao.find(id);
    }

    @Override
    public void update(ExperienceRule experienceRule) {
        experienceRuleDao.update(experienceRule);
    }

    @Override
    public int updateStatus(long id, byte status, byte preStatus) {
        return experienceRuleDao.updateByJpql("UPDATE ExperienceRule SET status=:status WHERE status=:preStatus AND id=:id",
                new String[]{"id", "status", "preStatus"}, new Object[]{id, status, preStatus});
    }
}
